<template>
	<view>
		<view class="">
			
		</view>
		<page-bg-liner></page-bg-liner>
		<view class="p-l-5 p-r-5 p-t-10 p-b-15 position-rel z-i-10">
			<view class="m-b-5" v-for="(item,index) in list" :key="index">
				<image :src="item" class="imgs" mode="" @tap.stop="$util.previewImg(list,index)"></image>
			</view>
		</view>
		<view class="" style="height: 120upx;"></view>
		<view class="bot-wrap">
			<!-- 保存图片 -->
			<!-- <view class="flex align-center" @click="savePosterPath()">
				<image src="/static/img/download.png" class="share-icon"></image>
			</view> -->
			<!-- 保存pdf -->
			<!-- <view class="flex align-center" @click="downloadPDF()">
				<image src="/static/img/save.png" class="share-icon"></image>pdf
			</view> -->
			
			<!-- 分享给好友 -->
			<view class="flex align-center" style="position: relative;" @click="shareFriend()">
				<image src="/static/img/wx-share.png" class="share-icon"></image>
			</view>
			<!-- 分享给朋友圈 -->
			<view class="flex align-center" style="position: relative;" @click="shareTimeline()">
				<image src="/static/img/wx-friend.png" class="share-icon"></image>
			</view>
		</view>
		
		<view class="mask" v-show="isShowMask" @click="isShowMask = false">
			<view class="flex justify-end" style="margin-top: 60upx;margin-right: 60upx;">
				<view class="" style="color: #fff;margin-top: 50upx;font-size: 34upx;">
					点击右上角更多进行分享~
				</view>
				<image src="/static/img/share1.png" mode="" style="height: 60upx;width: 60upx;"></image>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		components: {
			// cuCustom
		},
		data() {
			return {
				id: '',
				list: [],
				pdfList: [],
				info: {},
				shareType:'',//1好友 2朋友圈
				isShowMask:false,
				desc:''
			}
		},
		onLoad(option) {
			if (option.id) {
				this.id = option.id;
				this.getInfo();
			}
			
			let wxWlement = document.createElement('script')
			wxWlement.src = 'http://res.wx.qq.com/open/js/jweixin-1.6.0.js'
			document.body.appendChild(wxWlement)
		},
		async created() {
			const res = await this.getUserShareData();
			let wxData = res.data
			// 3. 初始化配置
			wx.config({
				debug: false, // 调试时开启
				appId: wxData.appId,
				timestamp: wxData.jsTimesTamp,
				nonceStr: wxData.jsNonceStr,
				signature: wxData.jsSignature,
				jsApiList: ['updateAppMessageShareData','updateTimelineShareData'] // 需要使用的接口列表
			});
			// 4. 处理配置结果
			wx.ready(() => {
				wx.updateAppMessageShareData({
					title: '精益管理-检查标准卡', // 自定义标题
					desc:this.desc,
					link: window.location.href, // 分享链接（当前页）
					imgUrl: 'https://apipic.leanplants.com/20211202175156.png', // 分享图标（需绝对路径）
					success: function () {
					    console.log('成功')
					}
				});
				wx.updateTimelineShareData({
					title: '精益管理-检查标准卡', // 自定义标题
					desc:this.desc,
					link: window.location.href, // 分享链接（当前页）
					imgUrl: 'https://apipic.leanplants.com/20211202175156.png', // 分享图标（需绝对路径）
					success: function () {
					    console.log('成功')
					}
				});
			});
			wx.error((res) => {
				console.error('微信配置失败:', res);
			});
		},
		methods: {
			shareFriend(){
				this.isShowMask = true
			},
			shareTimeline(){
				this.isShowMask = true
			},
			getInfo() {
				let data = {
					// type: 1,
					// id: this.id,
					standards_id:this.id
				}
				// this.$http('FivesManagement.InspectionStandardsPerson/personStandardsInfov2', data).then(res => {
				this.$http('FivesManagement.InspectionStandards/standardsDetailsPdf', data).then(res => {
					if (res.status == 200) {
						let datas = res.data;
						this.desc = datas.name
						this.list = datas.pdf_url ? datas.pdf_url.split(',') : [];
						this.pdfList = datas.pdf ? datas.pdf.split(',') : [];
					}
				})
			},
			// 获取到
			async getUserShareData() {
				// 1. 获取当前页面 URL（需去掉 # 后的部分）
				const currentUrl = window.location.href.split('#')[0];

				let data = {
					url: currentUrl
				}
				const wxData = await this.$http('UserManagement.Member/getPositioningTicket', data)
				return wxData
			},
			
			downloadByUrl(urlArr) {
				uni.showLoading({
					title: '保存中...',
					mask: true
				});
				let successCount = 0;
				let failCount = 0;

				// 递归下载函数
				const downloadNext = async (index) => {
					if (index >= urlArr.length) {
						// 所有文件下载完成
						uni.hideLoading();
						let message = failCount === 0 ?
							'保存成功' :
							`保存完成，成功${successCount}个，失败${failCount}个`;

						uni.showToast({
							title: message,
							icon: failCount === 0 ? 'success' : 'none',
							duration: 2000
						});
						return;
					}

					try {
						const url = urlArr[index];
						const res = await new Promise((resolve, reject) => {
							uni.downloadFile({
								url: url,
								success: resolve,
								fail: reject
							});
						});

						if (res.statusCode === 200) {
							// 获取文件名
							const fileName = url.substring(url.lastIndexOf('/') + 1);
							// 创建隐藏链接下载
							const link = document.createElement('a');
							link.href = res.tempFilePath;
							link.download = fileName;
							document.body.appendChild(link);
							link.click();
							document.body.removeChild(link);
							successCount++;
						} else {
							failCount++;
						}
					} catch (error) {
						failCount++;
						console.error('下载失败:', error);
					}

					// 继续下载下一个
					downloadNext(index + 1);
				};

				// 开始下载第一个文件
				downloadNext(0);
			},
			downloadPDF() {
				this.downloadByUrl(this.pdfList)
			},
			// 点击保存按钮事件
			savePosterPath() {
				if(this.list.length == 0){
					return
				}
				this.downloadByUrl(this.list)
			},
		}
	}
</script>

<style lang="less">
	.imgs {
		width: 730upx;
		height: 516upx;
	}

	.bot-wrap {
		width: 100%;
		background: #fff;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 99;
		padding: 0 30upx;
		height: 120upx;
		display: flex;
		align-items: center;
		justify-content: space-around;

		.bot-btn {
			width: 100%;
			height: 90upx;
			background: #529EFF;
			opacity: 1;
			border-radius: 20upx;
			font-size: 32upx;
			font-weight: bold;
			color: #fff;
			line-height: 90upx;
			text-align: center;
		}
	}

	.share-icon {
		width: 80upx;
		height: 80upx;
		padding: 10upx 20upx;
	}
	.mask{
		position: fixed;
		top: 0;
		z-index: 99999;
		height: 100%;
		width: 100%;
		background-color: #000000;
		opacity: 0.4;
	}
</style>